import axios,{ AxiosError, AxiosInstance, AxiosResponse,InternalAxiosRequestConfig } from "axios"

const configs = {
  timeout: 60000,
  headers: {
    "Content-Type": "application/json;charset=utf-8"
  },
  baseURL: ''
}

declare module 'axios' {
  export interface AxiosInstance {
    <T = any>(config: InternalAxiosRequestConfig):Promise<T>
    post<T = any>(url:string,data?:any,config? :AxiosResponse):Promise<T>
  }
}
class RequestHttp {
  service:AxiosInstance;
  constructor(){
    this.service = axios.create(configs)
    this.service.interceptors.request.use((config:InternalAxiosRequestConfig)=>{
      return config
    })
    this.service.interceptors.response.use((response:AxiosResponse)=>{
      return response.data
    },
    (error:AxiosError)=>{
        console.log(error,'返回的错误')
        const { response } = error;
        if(response){
          checkStatus(response.status)
        }
      }
    )
  }
  // 常规请求封装
  get(url: string, params? :object){
    return this.service.get(url, { params })
  }
  post(url: string, params? :object){
        return this.service.post(url, { params })
  }
}
const checkStatus=(status:number)=>{
  switch (status) {
    case 404:
      console.log('没找到接口')
      break;
    case 405:
      console.log('请求方式不对')
      break;
    case 504:
      console.log('服务器异常了')
      break;
    case 401:
      console.log('没有权限')
      break;
    default:
      console.warn('请求失败了')
      break;
  }
}
export default RequestHttp
